'use strict';
	angular.module('inventory.skuList', [])

	.controller('skuListCtrl'
			,['$rootScope', '$scope', '$uibModal', 'BizData', '$ocLazyLoad'
			   , f])
    function f($rootScope, $scope, $uibModal,BizData, $ocLazyLoad) {


		var Model = this;
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码
		var billType = 'WLGG';
		var billTypeName = '物料规格';

		var state;
		var status;
		var orderDate;
		
		var userId;
		var enterpriseNo;
		var enterpriseName;
		
   		
   		/**
   		name:bizData#onIndexChanged
   		description: <b>[回调型事件]</b>行记录变化
   		@param {object} event 
   		<br/><b>结构如下：</b>
   		<xmp> 
   		{
   		"source" : 组件的js对象,
   		"rowID" : 行Id,
   		"rowIndex" : 行索引
   		}
   		</xmp>	
   		*/
   		Model.dataMasterIndexChanged = function(event) {
			if(event.rowID!=null){
				Model.dataDetail.filter = "ItemProper.itemID='"+event.rowID+"'";
	       		Model.dataDetail.refreshData();
				//SKU
//				Model.dataSKU.groupID = event.rowID;
				//设置过滤条件
				Model.dataSKU.filter = " FileItem.fParent='"+event.rowID+"'"
				;
	       		Model.dataSKU.refreshData();
				
			}else{
				Model.dataDetail.clearData();
				Model.dataSKU.clearData();
			}
  		}
		
		var options = {};
		options.container = Model;
		options.concept = 'FileItem';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.creater = '/inventory/fileItem/list/create';
 		options.reader = '/inventory/fileItem/list/query';
		options.writer = '/inventory/fileItem/list/save';
		options.deleter = '/inventory/fileItem/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = "itemNo ASC";
		
		options.onIndexChanged = Model.dataMasterIndexChanged;
		
		Model.dataMaster = new BizData(options);

		//监视对象中的所有变动
		//Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////


		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataDetailAfterDelete = function(event) {
			/*
			//更新主表计数器（从表最大流水号）
			var dataMaster = Model.dataMaster;
			var masterRowID = dataMaster.getCurrentID();
			//更新主表中子表记录数
			dataMaster.setValue('rationSize', dataMaster.getValue('rationSize', masterRowID) -1, masterRowID);	
			*/
		}
		
		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataDetailIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataDetailDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataDetailValueChanged = function(event) {

		}

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataDetailBeforeNew = function(event) {
			// 明细数据新增之前
			// 检查主表中的数据是否完整
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			state = dataMaster.getValue('state', rowID);
			status = dataMaster.getValue('status', rowID);
			orderDate = dataMaster.getValue('orderDate', rowID);
			
			//////////////////////////////////////////////////////////////////////
			
			userId = dataMaster.getValue('userId', rowID);
			enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			enterpriseName = dataMaster.getValue('enterpriseName', rowID);

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataDetailAfterNew = function(event){
			var dataDetail = event.source;
			var rowID = event.id;

			dataDetail.setValue('state', state, rowID);
			dataDetail.setValue('status', status, rowID);
			dataDetail.setValue('orderDate', orderDate, rowID);

			dataDetail.setValue('systemCode', systemCode, rowID);
			dataDetail.setValue('billType', billType, rowID);
			dataDetail.setValue('billTypeName', billTypeName, rowID);

			dataDetail.setValue('userId', userId, rowID);
			dataDetail.setValue('enterpriseNo', enterpriseNo, rowID);
			dataDetail.setValue('enterpriseName', enterpriseName, rowID);

			dataDetail.setValue('fMasterID',dataDetail.fMasterID,rowID);
			/*
			//更新主表计数器（从表最大流水号）
			var dataMaster = Model.dataMaster;
			var masterRowID = dataMaster.getCurrentID();
			//更新主表中子表记录数
			dataMaster.setValue('rationSize', dataMaster.getValue('rationSize', masterRowID) + 1, masterRowID);	
			*/
		}

		Model.gridRowClick = function(event){
			
			
		}

		Model.gridRowDblClick = function(event){
			Model.edit();
		}
		
   		
		//特征列表
		var options = {};
		options.container = Model;
		options.concept = 'ItemProper';
		options.name = 'dataDetail';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.creater = '/inventory/itemProper/list/create';
 		options.reader = '/inventory/itemProper/list/query';
		options.writer = '/inventory/itemProper/list/save';
		options.deleter = '/inventory/itemProper/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = -1;

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataDetailIndexChanged;
		options.onBeforeNew = Model.dataDetailBeforeNew;
		options.onAfterNew = Model.dataDetailAfterNew;
		options.onBeforeDelete = Model.dataDetailBeforeDelete;
		options.onAfterDelete = Model.dataDetailAfterDelete;
		options.onValueChanged = Model.dataDetailValueChanged;
		options.onDataChanged = Model.dataDetailDataChanged;
		
		Model.dataDetail = new BizData(options);
		//监视对象中的所有变动
		Model.dataDetail.deregRows = $scope.$watch('Model.dataDetail.rows',Model.dataDetail.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		var options = {};
		options.container = Model;
		options.concept = 'FileItem';
		options.name = 'dataSKU';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.creater = '/inventory/fileItem/list/create';
 		options.reader = '/inventory/fileItem/list/query';
		options.writer = '/inventory/fileItem/list/save';
		options.deleter = '/inventory/fileItem/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = -1;
		options.orderBy = "sortNo ASC";
		
		Model.dataSKU = new BizData(options);
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////
		//接收调用的参数
//		Model.params = $rootScope.$stateParams;  
		

		//设置过滤条件
		Model.dataMaster.filter = "FileItem.configType=1";

		//刷新数据
	    Model.dataMaster.refreshData();

		////////////////////启动执行结束///////////////////////////////////////////////////
		
		///////////////////子表按钮组开始///////////////////////////////////////////////////
		//增加
		Model.addrow = function(){
		     var options = {
			         index : Model.dataDetail.getCount(),
			         defaultValues : [
			             {
//			            	 ,requirementDate:systemService.getCurrentDate(false)
			            	 
			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataDetail.newData(options);
		};
		
		Model.delrow = function() {
			 if(Model.dataDetail.directDeleteMode){
				//直接删除
				 if(Model.dataDetail.deleteData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.refreshData();
				 }
			 }else{
				//前台移除
				 if(Model.dataDetail.removeData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.recordState = 'delete';
				 }
			 }
		};
		
		Model.importFromClass = function(){
			alert('建设中......');
		};
		
		//修改
		Model.editrow = function(){
			Model.dataDetail.editData();
		}
		
		//保存
		Model.saverow = function(){
			Model.dataDetail.saveData();
		}

		//取消保存
		Model.saverowCancel = function() {
			Model.dataDetail.editCancel();
		}
		
		///////////////////子表按钮组结束///////////////////////////////////////////////////
		

		//添加(调用对话框)
	    Model.add = function() {
	    	var skuCount = Model.dataSKU.getCount();
	    	if(skuCount>0){
	    		alert('生成之前必须清空列表！');
	    		return;
	    	}
	    	
	    	var dataMaster = Model.dataMaster;
	    	var rowID = dataMaster.getCurrentID();
	    	if(rowID!=null){
	    		//生成SKU
	    		//console.log('rowID-->',rowID);
	    		
	    		$.ajax({
	                type: "POST",
	                async : true,
	                url: $rootScope.getProjectName() + "/inventory/fileItem/sku/skuInsert",
	                data: rowID,// "{}",
	                contentType: "application/json; charset=utf-8",
	                dataType: "json",
//	                processData: false,
	                success: function (data) {
	                    // Play with returned data in JSON format
	                    console.log('success',data);
	                    if(data==-1){
	                    	alert('物料编码不存在');
	                    }else if(data==-2){
	                    	alert('物料分类不存在');
	                    }else if(data>=0){
	        				//设置过滤条件
	        				Model.dataSKU.filter = " FileItem.fParent='"+rowID+"'"
	        				;
	        	       		Model.dataSKU.refreshData();
	        	       		$scope.$apply();
	                    	alert('成功添加'+data+'条记录！');
	                    }
	                },
	                error: function (msg) {
	                    console.log('error',msg);
	                    alert('操作失败，请检查网络是否正常！');
	                }
	            });
	    	}
		};

		//修改
		Model.edit = function() {
			//打开对话框
			var index = Model.dataSKU.getCurrentIndex();
			var row = Model.dataSKU.rows[index];

			var options = {};
			
			options.recordState = 'edit';
			options.id = row.fID.value;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            templateUrl: $rootScope.getProjectName() + '/inventory/fileItem/single',  
	            controller: 'fileItemSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '修改'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileItem/single')
		        }
	        });  
	        //模态窗口打开之后执行的事件
	        modalInstance.opened.then(function(){
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	             Model.dataMaster.refreshPageData();
//	             Model.dataMaster.currentIndex = index;
	        }, function (reason) {  
	        });  
				
		};


		//（删除）
		Model.remove = function(){
			var ids = new Array();
			for(var index=0;index<Model.dataSKU.rows.length;index++){
				if(Model.dataSKU.rows[index].userdata.checked){
					ids.push(Model.dataSKU.rows[index].fID.value);
				}
			}
			if(ids.length<=0){
            	$rootScope.addAlert('info','请选择需要删除的行。');
            	return;
			}
			Model.dataSKU.deleteData(ids);
			Model.dataSKU.refreshData();
		}

		//清空(调用对话框)
	    Model.clear = function() {
	    	
	    	var dataMaster = Model.dataMaster;
	    	var rowID = dataMaster.getCurrentID();
	    	if(rowID!=null){
	    		//生成SKU
	    		//console.log('rowID-->',rowID);
	    		var options = {};
	    		options.itemID = rowID;
	    		
	    		$.ajax({
	                type: "GET",
	                async : false,
	                url: $rootScope.getProjectName() + "/inventory/fileItem/sku/skuClear",
	                data: options,//rowID,// "{}",
	                contentType: "application/json; charset=utf-8",
	                dataType: "json",
//	                processData: false,
	                success: function (data) {
	                    // Play with returned data in JSON format
	                    console.log('success',data);
	                    if(data>=0){
	        				//设置过滤条件
	        				Model.dataSKU.filter = " FileItem.fParent='"+rowID+"'"
	        				;
	        	       		Model.dataSKU.refreshData();
	                    	alert('成功！');
	                    }
	                },
	                error: function (msg) {
	                    console.log('error',msg);
	                    alert('操作失败，请检查网络是否正常！');
	                }
	            });
	    	}
		};

	    //表格标题中的选择框ng-model
	    $scope.checkboxValue = false;
	    //表格标题中的选择对话框click事件
	    Model.checkboxClick = function () {  
			for(var index=0;index<Model.dataSKU.rows.length;index++){
				Model.dataSKU.rows[index].userdata.checked=$scope.checkboxValue;
			}
	    };    


		
		return Model;
	}	
	
